﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;

namespace HostDetector
{
    public class Pinger
    {
        private IPEndPoint ip;

        public IPEndPoint Ip
        {
            get { return ip; }
            set { ip = value; }
        }
        Stopwatch stopwatch = new Stopwatch();
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        byte[] pingMessage;

        public byte[] PingMessage
        {
            get { return pingMessage; }
            set { pingMessage = value; }
        }
        byte[] buffer = new byte[65536];
        
        public delegate void PingHandler(long ping);
        public event PingHandler PingEvent;
        public Pinger()
        {
            Thread thread = new Thread(pingLoop);
            thread.Start();


        }

        private void pingLoop()
        {
            while (true)
            {
                if (ip != null)
                {

                    try
                    {

                        while (socket.Available > 0)
                            socket.Receive(buffer);
                        stopwatch.Restart();
                        socket.SendTo(pingMessage, ip);
                        socket.ReceiveTimeout = 1000;
                        socket.Blocking = true;
                        socket.Receive(buffer);
                        while(socket.Available > 0)
                            socket.Receive(buffer);
                        stopwatch.Stop();
                        PingEvent(stopwatch.ElapsedMilliseconds);
                    }
                    catch
                    { 
                        PingEvent(999); 
                    }
                    
                }
                    

                Thread.Sleep(1000);
            }
        }

    }
}
